<template>
  <el-dialog
    v-model="visible"
    title="批量分配资产"
    width="800px"
    :close-on-click-modal="false"
    top="5vh"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="目标部门" prop="department_name">
        <el-select
          v-model="formData.department_name"
          placeholder="请选择目标部门"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="dept in selectedDepartments"
            :key="dept.id"
            :label="`${dept.department_name} (${dept.department_code})`"
            :value="dept.department_name"
          />
        </el-select>
        <div class="form-hint">💡 从已选择的部门中选择一个作为目标部门</div>
      </el-form-item>

      <el-form-item label="分配类型" prop="assignment_type">
        <el-radio-group v-model="formData.assignment_type">
          <el-radio label="ai_inference">AI推断分配</el-radio>
          <el-radio label="manual_confirm">手工确认分配</el-radio>
        </el-radio-group>
        <div class="form-hint">
          💡
          AI推断分配更新responsible_department字段，手工确认分配更新confirmed_department字段
        </div>
      </el-form-item>

      <el-form-item label="资产列表" prop="asset_ids">
        <el-input
          v-model="assetIdsText"
          type="textarea"
          :rows="6"
          placeholder="请输入资产ID，每行一个，例如：&#10;123&#10;124&#10;125"
          @input="handleAssetIdsInput"
        />
        <div class="form-hint">
          💡 请输入要分配的资产ID，每行一个，已输入
          {{ formData.asset_ids.length }} 个资产ID
        </div>
      </el-form-item>

      <el-form-item label="分配者" prop="assigned_by">
        <el-input
          v-model="formData.assigned_by"
          placeholder="请输入分配者（可选）"
          maxlength="50"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确定分配
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElForm, ElMessageBox } from "element-plus";
import type { FormRules } from "element-plus";
import { batchAssignAssetsToDepartments } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  selectedDepartments: {
    type: Array as () => any[],
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const submitting = ref(false);
const assetIdsText = ref("");

// 表单数据
const formData = reactive({
  department_name: "",
  assignment_type: "ai_inference" as "ai_inference" | "manual_confirm",
  asset_ids: [] as number[],
  assigned_by: "",
});

// 表单验证规则
const formRules: FormRules = {
  department_name: [
    { required: true, message: "请选择目标部门", trigger: "change" },
  ],
  assignment_type: [
    { required: true, message: "请选择分配类型", trigger: "change" },
  ],
  asset_ids: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error("请输入至少一个资产ID"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 处理资产ID输入
const handleAssetIdsInput = (value: string) => {
  // 解析资产ID（支持换行、逗号、空格分隔）
  const ids = value
    .split(/[\n,\s]+/)
    .map((id) => id.trim())
    .filter((id) => id && /^\d+$/.test(id))
    .map((id) => parseInt(id, 10));
  formData.asset_ids = ids;
};

// 监听弹窗打开，初始化表单
watch(visible, (val) => {
  if (val) {
    if (props.selectedDepartments.length > 0) {
      formData.department_name = props.selectedDepartments[0].department_name;
    }
    formData.assignment_type = "ai_inference";
    formData.asset_ids = [];
    formData.assigned_by = "";
    assetIdsText.value = "";
    formRef.value?.clearValidate();
  }
});

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (formData.asset_ids.length === 0) {
      ElMessage.warning("请输入至少一个资产ID");
      return;
    }

    // 确认对话框
    await ElMessageBox.confirm(
      `确定要将 ${formData.asset_ids.length} 个资产分配到【${formData.department_name}】吗？`,
      "确认分配",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    submitting.value = true;

    // 构建分配列表
    const assignments = formData.asset_ids.map((assetId) => ({
      asset_id: assetId,
      department_name: formData.department_name,
      assignment_type: formData.assignment_type,
    }));

    const result = await batchAssignAssetsToDepartments({
      assignments,
      assigned_by: formData.assigned_by || undefined,
    });

    if (result.code === 200 && result.data) {
      const {
        success_count,
        failed_count,
        total_count,
        success_rate,
        failed_assignments,
        success_assignments,
      } = result.data;

      // 显示总体结果
      if (failed_count === 0) {
        ElMessage.success(
          `批量分配成功：成功 ${success_count} 个，失败 ${failed_count} 个`
        );
      } else if (success_count === 0) {
        ElMessage.error(
          `批量分配失败：成功 ${success_count} 个，失败 ${failed_count} 个`
        );
      } else {
        ElMessage.warning(
          `批量分配完成：成功 ${success_count} 个，失败 ${failed_count} 个`
        );
      }

      // 显示失败详情
      if (failed_assignments && failed_assignments.length > 0) {
        const failedMessages = failed_assignments
          .map(
            (r: any) =>
              `资产ID ${r.asset_id}: ${r.error || r.message || "分配失败"}`
          )
          .join("\n");
        ElMessageBox.alert(failedMessages, "分配失败详情", {
          confirmButtonText: "确定",
          type: "warning",
        });
      }

      emit("success");
      emit("update:modelValue", false);
    } else {
      ElMessage.error(result.message || "批量分配失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量分配失败");
    }
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped lang="scss">
.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.5;
}
</style>
